package com.jielin.handling.service.policeplatform.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jielin.handling.db.InquestionsMapper;
import com.jielin.handling.entity.alarmlog.AlarmLog;
import com.jielin.handling.entity.criminalcase.CriminalCase;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.police.Cases;
import com.jielin.handling.entity.police.ReceiveDeal;
import com.jielin.handling.entity.policeplatform.*;
import com.jielin.handling.entity.unit.OrganizationVo;
import com.jielin.handling.entity.unit.UnitInfo;
import com.jielin.handling.entity.unit.UnitVo;
import com.jielin.handling.entity.vo.*;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.material.MaterialFileMapper;
import com.jielin.handling.mapper.material.MaterialTypeDocumentMapper;
import com.jielin.handling.mapper.policeplatform.PolicePlatformMapper;
import com.jielin.handling.mapper.unit.UnitMapper;
import com.jielin.handling.redis.RedisTemplateX;
import com.jielin.handling.service.casegoods.CaseGoodsAuditResultService;
import com.jielin.handling.service.policeplatform.PolicePlatformService;
import com.jielin.handling.service.unit.UnitService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzhang
 * @date 2019/5/7 - 19:28
 */
@Service
@Slf4j
public class PolicePlatformServiceImpl implements PolicePlatformService {

    // 获取httpclient实例
    private HttpClientForJL httpClientForJL = new HttpClientForJL();

    // 获取objectmapper工具类实例
    private static ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    PolicePlatformMapper policePlatformMapper;
    @Autowired
    private InquestionsMapper inquestionsMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private UnitService unitService;
    @Autowired
    CaseGoodsAuditResultService caseGoodsAuditResultService;

    @Autowired
    private XskyService xskyService;
    @Autowired
    private MaterialTypeDocumentMapper maTypeDocumentMapper;
    @Autowired
    private MaterialFileMapper mfMapper;
    @Autowired
    PolicePlatformService platformService;
    @Autowired
    private RedisTemplateX redisTemplateX;

    @Override
    public List<String> selectUnicode() {

        return policePlatformMapper.selectUnicode();

    }

    @Override
    public void requestPoliceData() {
        System.out.println("开始执行获取警综数据定时任务!" + new Date());

        List<String> list = policePlatformMapper.selectUnicode();
        System.out.println(list);

        for (String code : list) {
            //准备发送请求
            getPoliceDataByUnitCode(code);
            //getReceiveDealByUnitCode(code);

        }

        System.out.println("任务执行结束!" + new Date());
    }

    @Override
    public void requestExamination() {
        System.out.println("开始执行执法考核统计定时任务!" + new Date());

        List<String> list = policePlatformMapper.selectUnicode();
        System.out.println(list);
        //获取某单位的案件最大入库时间
        String registTime = "";
        //遍历单位编号
        for (String code : list) {
            //通过单位编号获取该单位最大入库时间
            String registTime1 = policePlatformMapper.getRegistTime(code);
            //获取月份集合

            List<String> date = PolicePlatformServiceImpl.getMonthBetween();
            for (String str : date) {
                grtAssessment(code, str, registTime1);
            }

        }

        System.out.println("任务执行结束!" + new Date());
    }

    /**
     * @param "minDate" 最小时间  2015-01
     * @param "maxDate" 最大时间 2015-10
     * @return 日期集合 格式为 年-月
     * @throws Exception
     */

    public static List<String> getMonthBetween() {
        List<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
            Calendar c1 = Calendar.getInstance();
            c1.setTime(new Date());
            c1.add(Calendar.YEAR, -2);
            String minDate = sdf.format(c1.getTime());
            String maxDate = (new SimpleDateFormat("yyyy-MM")).format(new Date());

            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();

            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void requestSuperiorOrg() {
        // 获取警综最新单位信息
        List<OrganizationVo> list = inquestionsMapper.requestSuperiorOrg();
        if (list.size() == 0) {
            return;
        }
        // 添加不存在的单位
        list.stream().forEach(org -> {
            String orgId = policePlatformMapper.orgExist(org.getHandleUnitCode());
            if (StringUtil.isEmpty(orgId)) {
                org.setOrgId(StringUtil.generatorUUID());
                org.setSuperId("");
                policePlatformMapper.insertOrg(org);
                log.info("添加成功：" + org.getOrgName());
            }
        });
        // 同步父id
        unitMapper.findUnitInfoBySuperiorIdIsNull().stream().forEach(organization -> {
            // 根据单位编号查询父id
            String parentId = unitMapper.findParentIdByUnitCode(organization.getHandleUnitCode());
            if (!StringUtil.isEmpty(parentId)) {
                organization.setSuperiorId(parentId);
                // 修改父id
                unitMapper.updateUnitSuperiorId(organization);
            }
        });
        // 获取所有新增的单位信息，添加权限、人员、笔录模板信息
        unitMapper.findUnitINfoIsNew().stream().forEach(newOrg -> {
            unitService.addUnitInfo(newOrg);
        });
    }

    @Override
    public Map<String, Object> selectVideoByUnitCode(JSONObject queryCondition) {
        //查询当前机构和子机构编号
        List<OrganizationVo> lists = caseGoodsAuditResultService.findUnitInfoByUnitCodeS(queryCondition.getString("unitcode"));
        List<String> strList = new ArrayList<>();
        for (OrganizationVo vo : lists) {
            strList.add(vo.getHandleUnitCode());
        }
        String str1 = "";
        String array[] = null;
        for (int i = 0; i < strList.size(); i++) {
            str1 += strList.get(i) + ",";
            array = str1.split(",");
        }
        //查询当前单位编号下的视频统计
        List<Map<String, Object>> list = policePlatformMapper.selectVideoByUnitCode(array);
        Map<String, Object> map = new HashMap<>();
        if(list.size()!=0) {
            //今年的数据
            int[] thisYear = new int[]{
                    Integer.parseInt(list.get(0).get("thisYear").toString()),
                    Integer.parseInt(list.get(1).get("thisYear").toString()),
                    Integer.parseInt(list.get(2).get("thisYear").toString()),
                    Integer.parseInt(list.get(3).get("thisYear").toString()),
                    Integer.parseInt(list.get(4).get("thisYear").toString())
            };
            //去年的数据
            int[] lastYear = new int[]{
                    Integer.parseInt(list.get(0).get("lastYear").toString()),
                    Integer.parseInt(list.get(1).get("lastYear").toString()),
                    Integer.parseInt(list.get(2).get("lastYear").toString()),
                    Integer.parseInt(list.get(3).get("lastYear").toString()),
                    Integer.parseInt(list.get(4).get("lastYear").toString())
            };
            //前年的数据
            int[] beforeYear = new int[]{
                    Integer.parseInt(list.get(0).get("beforeYear").toString()),
                    Integer.parseInt(list.get(1).get("beforeYear").toString()),
                    Integer.parseInt(list.get(2).get("beforeYear").toString()),
                    Integer.parseInt(list.get(3).get("beforeYear").toString()),
                    Integer.parseInt(list.get(4).get("beforeYear").toString())
            };
            map.put("thisYear", thisYear);
            map.put("lastYear", lastYear);
            map.put("beforeYear", beforeYear);
/*        //车载视频
        map.put("carVideo",list.get(0));
        //公共视频
        map.put("publicVideo",list.get(1));
        //其他视频
        map.put("otherVideo",list.get(2));
        //办案视频
        map.put("detailedVideo",list.get(3));
        //执法视频
        map.put("recorderVideo",list.get(4));*/
        }
        String[] head = new String[]{"车载视频", "公共视频", "其他视频", "办案视频", "执法视频"};
        map.put("head", head);
        return map;
    }

    @Override
    public Map<String, Object> selectCaseTypeSum(JSONObject queryCondition) {
        //查询当前机构和子机构编号
        List<OrganizationVo> lists = caseGoodsAuditResultService.findUnitInfoByUnitCodeS(queryCondition.getString("unitcode"));
        List<String> strList = new ArrayList<>();
        for (OrganizationVo vo : lists) {
            strList.add(vo.getHandleUnitCode());
        }
        String str1 = "";
        String array[] = null;
        for (int i = 0; i < strList.size(); i++) {
            str1 += strList.get(i) + ",";
            array = str1.split(",");
        }

        //查询当前单位编号下的案件类型统计
        List<Map<String, Object>> list = policePlatformMapper.selectCaseTypeSum(array);
        Map<String, Object> map = new HashMap<>();

        BigDecimal thisYearSum = new BigDecimal(0);
        BigDecimal lastYearSum = new BigDecimal(0);
        BigDecimal beforeYearSum = new BigDecimal(0);

        for (int i = 0; i < list.size(); i++) {
            thisYearSum = thisYearSum.add((BigDecimal) list.get(i).get("thisYear"));
            lastYearSum = lastYearSum.add((BigDecimal) list.get(i).get("lastYear"));
            beforeYearSum = beforeYearSum.add((BigDecimal) list.get(i).get("beforeYear"));
        }
        int[] thisYear = new int[3];
        int[] lastYear = new int[3];
        int[] beforeYear = new int[3];
        //百分比
        BigDecimal bfb = new BigDecimal(100);
        for (int i = 0; i < list.size(); i++) {

            //今年的数据的百分比
            BigDecimal thisYearSj = (BigDecimal) list.get(i).get("thisYear");
            if (thisYearSj.intValue() != 0) {
                BigDecimal thisYear1 = thisYearSj.divide(thisYearSum, 2, RoundingMode.HALF_UP).multiply(bfb);
                thisYear[i] = thisYear1.intValue();
            } else {
                thisYear[i] = 0;
            }
            //去年数据的百分比
            BigDecimal lastYearSj = (BigDecimal) list.get(i).get("lastYear");
            if (lastYearSj.intValue() != 0) {
                BigDecimal lastYear1 = lastYearSj.divide(lastYearSum, 2, RoundingMode.HALF_UP).multiply(bfb);
                lastYear[i] = lastYear1.intValue();
            } else {
                lastYear[i] = 0;
            }
            //前年数据的百分比
            BigDecimal beforeYearSj = (BigDecimal) list.get(i).get("beforeYear");
            if (beforeYearSj.intValue() != 0) {
                BigDecimal beforeYear1 = beforeYearSj.divide(beforeYearSum, 2, RoundingMode.HALF_UP).multiply(bfb);
                beforeYear[i] = beforeYear1.intValue();
            } else {
                beforeYear[i] = 0;
            }
        }
        String[] head = new String[]{"刑事案件", "民事案件", "行政案件"};
        map.put("thisYear", thisYear);
        map.put("lastYear", lastYear);
        map.put("beforeYear", beforeYear);
        map.put("head", head);
        return map;
    }

    @Override
    public Map<String, Object> selectFileTransferSum(JSONObject queryCondition) {
        //查询当前机构和子机构编号
        List<OrganizationVo> lists = caseGoodsAuditResultService.findUnitInfoByUnitCodeS(queryCondition.getString("unitcode"));
        List<String> strList = new ArrayList<>();
        for (OrganizationVo vo : lists) {
            strList.add(vo.getHandleUnitCode());
        }
        String str1 = "";
        String array[] = null;
        for (int i = 0; i < strList.size(); i++) {
            str1 += strList.get(i) + ",";
            array = str1.split(",");
        }

        //查询当前单位编号下的卷宗类型统计
        List<Map<String, Object>> list = policePlatformMapper.selectFileTransferSum(array);
        Map<String, Object> map = new HashMap<>();
        //今年的数据
/*        int[] thisYear =  new int[list.size()];
        //去年的数据
        int[] lastYear =  new int[list.size()];
        //前年的数据
        int[] beforeYear =  new int[list.size()];*/

        //今年的数据
        JSONObject thisYear = new JSONObject();
        //去年的数据
        JSONObject lastYear = new JSONObject();
        //前年的数据
        JSONObject beforeYear = new JSONObject();

        for (int i = 0; i < list.size(); i++) {

            if (i == 0) {
                thisYear.put("one", Integer.parseInt(list.get(i).get("thisYear").toString()));
                lastYear.put("one", Integer.parseInt(list.get(i).get("lastYear").toString()));
                beforeYear.put("one", Integer.parseInt(list.get(i).get("beforeYear").toString()));
            }
            if (i == 1) {
                thisYear.put("two", Integer.parseInt(list.get(i).get("thisYear").toString()));
                lastYear.put("two", Integer.parseInt(list.get(i).get("lastYear").toString()));
                beforeYear.put("two", Integer.parseInt(list.get(i).get("beforeYear").toString()));
            }
            if (i == 2) {
                thisYear.put("three", Integer.parseInt(list.get(i).get("thisYear").toString()));
                lastYear.put("three", Integer.parseInt(list.get(i).get("lastYear").toString()));
                beforeYear.put("three", Integer.parseInt(list.get(i).get("beforeYear").toString()));
            }
            if (i == 3) {
                thisYear.put("four", Integer.parseInt(list.get(i).get("thisYear").toString()));
                lastYear.put("four", Integer.parseInt(list.get(i).get("lastYear").toString()));
                beforeYear.put("four", Integer.parseInt(list.get(i).get("beforeYear").toString()));
            }
        }
        //今年的数量总和
        int thisYearSum = thisYear.getIntValue("one") + thisYear.getIntValue("two") + thisYear.getIntValue("three") + thisYear.getIntValue("four");
        //去年的数量总和
        int lastYearSum = lastYear.getIntValue("one") + lastYear.getIntValue("two") + lastYear.getIntValue("three") + lastYear.getIntValue("four");
        //前年的数量总和
        int beforeYearSum = beforeYear.getIntValue("one") + beforeYear.getIntValue("two") + beforeYear.getIntValue("three") + beforeYear.getIntValue("four");
        //总和数据
        int[] all = new int[]{thisYearSum, lastYearSum, beforeYearSum};
        //年份
        String[] year = new String[]{getYear(-2), getYear(-1), getYear(0)};

        map.put("thisYear", thisYear);
        map.put("lastYear", lastYear);
        map.put("beforeYear", beforeYear);
        String[] head = new String[]{"未入柜", "在柜", "借阅", "移交"};
        map.put("all", all);
        map.put("year", year);
        map.put("head", head);
        return map;
    }

    //查询地图数据案件总数统计
    @Override
    public Map<String, Object> selectMapCaseSum(JSONObject queryCondition) {

        Map<String, Object> map = new HashMap<>();
        //今年的数据
        JSONObject thisYear = new JSONObject();
        //去年的数据
        JSONObject lastYear = new JSONObject();
        //前年的数据
        JSONObject beforeYear = new JSONObject();

        //查询地图数据案件总数统计
        List<Map<String, Object>> list = policePlatformMapper.selectMapCaseSum();

        for (int i = 0; i < list.size(); i++) {

            if (i == 0) {
                thisYear.put("恩施市", list.get(i).get("thisYear"));
                lastYear.put("恩施市", list.get(i).get("lastYear"));
                beforeYear.put("恩施市", list.get(i).get("beforeYear"));
            }
            if (i == 1) {
                thisYear.put("来凤县", list.get(i).get("thisYear"));
                lastYear.put("来凤县", list.get(i).get("lastYear"));
                beforeYear.put("来凤县", list.get(i).get("beforeYear"));
            }
            if (i == 2) {
                thisYear.put("建始县", list.get(i).get("thisYear"));
                lastYear.put("建始县", list.get(i).get("lastYear"));
                beforeYear.put("建始县", list.get(i).get("beforeYear"));
            }
            if (i == 3) {
                thisYear.put("利川市", list.get(i).get("thisYear"));
                lastYear.put("利川市", list.get(i).get("lastYear"));
                beforeYear.put("利川市", list.get(i).get("beforeYear"));
            }
            if (i == 4) {
                thisYear.put("巴东县", list.get(i).get("thisYear"));
                lastYear.put("巴东县", list.get(i).get("lastYear"));
                beforeYear.put("巴东县", list.get(i).get("beforeYear"));
            }
            if (i == 5) {
                thisYear.put("鹤峰县", list.get(i).get("thisYear"));
                lastYear.put("鹤峰县", list.get(i).get("lastYear"));
                beforeYear.put("鹤峰县", list.get(i).get("beforeYear"));
            }
            if (i == 6) {
                thisYear.put("咸丰县", list.get(i).get("thisYear"));
                lastYear.put("咸丰县", list.get(i).get("lastYear"));
                beforeYear.put("咸丰县", list.get(i).get("beforeYear"));
            }
            if (i == 7) {
                thisYear.put("宣恩县", list.get(i).get("thisYear"));
                lastYear.put("宣恩县", list.get(i).get("lastYear"));
                beforeYear.put("宣恩县", list.get(i).get("beforeYear"));
            }

        }
        //年份
        String[] year = new String[]{getYear(-2), getYear(-1), getYear(0)};
        map.put("thisYear", thisYear);
        map.put("lastYear", lastYear);
        map.put("beforeYear", beforeYear);
        map.put("year", year);
        return map;
    }

    private static final List<OrganizationVo> units = new ArrayList<>();

    static {
        units.add(OrganizationVo.builder().handleUnitCode("422801000000").orgName("恩施市").build());
        units.add(OrganizationVo.builder().handleUnitCode("422802000000").orgName("利川市").build());
        units.add(OrganizationVo.builder().handleUnitCode("422826000000").orgName("咸丰县").build());
        units.add(OrganizationVo.builder().handleUnitCode("422827000000").orgName("来凤县").build());
        units.add(OrganizationVo.builder().handleUnitCode("422825000000").orgName("宣恩县").build());
        units.add(OrganizationVo.builder().handleUnitCode("422822000000").orgName("建始县").build());
        units.add(OrganizationVo.builder().handleUnitCode("422828000000").orgName("鹤峰县").build());
        units.add(OrganizationVo.builder().handleUnitCode("422823000000").orgName("巴东县").build());
    }

    @Override
    public List<Map<String, Object>> selectMapCaseSums(JSONObject queryCondition) {
        List<Map<String, Object>> result = new ArrayList<>();
        // 查询所有单位信息
        List<OrganizationVo> organizationVos = unitMapper.findAllUnitInfo();
        List<OrganizationVo> Organization = unitMapper.findChildByUnitcode(queryCondition.getString("unitcode"));
//        units.forEach(unit -> {
//            result.put(unit.getOrgName(), policePlatformMapper.selectMapCaseSums(
//                    getChildCode(unit.getHandleUnitCode(), new ArrayList<>(), organizationVos)));
//        });

        Organization.forEach(org -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name",org.getOrgName());
            String[] val = new String[3];
            val[0] = org.getLongitude();
            val[1] = org.getLatitude();
            List<String> unitCodes = getChildCode(org.getHandleUnitCode(), new ArrayList<>(), organizationVos);
            val[2] = "" + policePlatformMapper.selectMapCaseSums(unitCodes);
            map.put("value", val);
            int num = unitMapper.findChildUnitNumById(org.getOrgId());
            if(num>0){
                List<OrganizationVo> childOrg = unitMapper.findChildByUnitcode(org.getHandleUnitCode());
                List<Map<String, Object>> list = new ArrayList<>();
                childOrg.forEach(child -> {
                    Map<String, Object> childs = new HashMap<>();
                    childs.put("name",child.getOrgName());
                    String[] c = new String[3];
                    c[0] = child.getLongitude();
                    c[1] = child.getLatitude();
                    c[2] = "" + policePlatformMapper.selectMapCaseSums(getChildCode(child.getHandleUnitCode(), new ArrayList<>(), organizationVos));
                    childs.put("value",c);
                    list.add(childs);
                });
                map.put("child", list);
            }
            result.add(map);
        });
        organizationVos.clear();
        return result;
    }

    /**
     * 递归查询本单位及其所有子单位编号
     *
     * @param superiorCode    父编号
     * @param childListEX     返回数据
     * @param organizationVos 单位数据
     * @return
     */
    private List<String> getChildCode(String superiorCode, List<String> childListEX, List<OrganizationVo> organizationVos) {
        if (!StringUtil.isEmpty(superiorCode)) {
            childListEX.add(superiorCode);
            // 移除已添加的元素
            organizationVos = organizationVos.stream().filter(item ->
                    !superiorCode.equals(item.getHandleUnitCode())).collect(Collectors.toList());
            // 查询当前单位子单位信息
            List<String> thisChildO = organizationVos.stream()
                    .filter(item -> superiorCode.equals(item.getSuperiorCode()))
                    .map(OrganizationVo::getHandleUnitCode).collect(Collectors.toList());

            if (thisChildO.size() > 0) {
                for (String childCode : thisChildO) {
                    getChildCode(childCode, childListEX, organizationVos);
                }
            }
        }
        return childListEX;
    }

    @Override
    public Map<String, Object> selectStatementCaseSum(JSONObject queryCondition) {
        //查询案情信息統計
        List<Map<String, Object>> list = policePlatformMapper.selectStatementCaseSum();
        Map<String, Object> map = new HashMap<>();
        map.put("sum", list);
        return map;
    }

    public String getYear(int amount) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, amount);
        Date y = c.getTime();
        String year = format.format(y);
        return year;
    }

    @Override
    public Map<String, Object> findPassCaseByUnitCode(String[] array) {
        List<Map<String, Object>> list = policePlatformMapper.findPassCaseByUnitCode(array);
        return null;
    }

    /**
     * 发送请求获取接处警信息
     *
     * @throws Exception
     */
    public void getReceiveDealByUnitCode(String unitCode) {
        String maxTime = "";
        maxTime = policePlatformMapper.findMaxTime(unitCode);
        System.out.println(maxTime);
        Map<String, Object> map = new HashMap<>();
        map.put("unitCode", unitCode);
        map.put("registTime", maxTime);
        List<Map> maps = inquestionsMapper.getReceiveDealByUnitCode(map);//通过单位编号查询最大时间之外的所有接处警信息
        if (maps.size() == 0) {
            return;
        }
        List<ReceiveDeal> receiveDeals = new ArrayList<>();
        for (Map temp : maps) {
            //将接处警信息Map对象转换为ReceiveDeal对象
            String s = null;
            try {
                s = objectMapper.writeValueAsString(temp);//将对象转换为json   DATE_FORMAT_MINUS
                ReceiveDeal receiveDeal = objectMapper.readValue(s, ReceiveDeal.class);//将json字符串解析为实体类对象
                if (receiveDeal != null) {
                    //验证此接处警是否已插入
                    int exist = policePlatformMapper.verifyReceiveDealExist(receiveDeal.getAlarmCode());
                    if (exist == 0) {
                        receiveDeal.setId(StringUtil.generatorUUID());
                        receiveDeals.add(receiveDeal);
                    }
                }
            } catch (JsonProcessingException e) {
                System.out.println("json解析异常");
            } catch (IOException e) {
                System.out.println("对象解析转换异常");
            }

        }
        //批量插入接处警所有信息
        if (receiveDeals.size() > 0) {
            policePlatformMapper.insertReceiveDeal(receiveDeals);
        }
    }

    /**
     * 发送请求获取警综相关案件信息
     *
     * @throws Exception
     */
    public void getPoliceDataByUnitCode(String unitCode) {
        //System.out.println("传入单位编号2!" +unitCode);
        String registTime1 = "";
        Long registTime = null;
        //获取某单位的案件最大入库时间
        registTime1 = policePlatformMapper.findMaxRKSJ(unitCode);
        if (registTime1 != null) {
            try {
                registTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(registTime1).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        System.out.println(registTime);
        Map<String, Object> map = new HashMap<>();
        //存入查询的单位编码和时间
        map.put("unitCode", unitCode);
        map.put("registTime", registTime);
        System.out.println("案件和时间集合3！！！！！！------------------------------------------------------------------" + map);

        List<Map> maps = inquestionsMapper.getCaseByUnitCode(map);//通过单位编号查询最大时间之外的所有案件信息
        System.out.println("案件信息4》》》》》》》》》》》》》》》》》》" + maps + "==========================================================================");
        if (maps.size() == 0) {
            return;
        }
        List<Cases> cases = new ArrayList<>();
        for (Map temp : maps) {
            //将案件信息Map对象转换为Case对象
            String s = null;
            try {
                s = objectMapper.writeValueAsString(temp);//将对象转换为json   DATE_FORMAT_MINUS
                Cases anjian = objectMapper.readValue(s, Cases.class);//将json字符串解析为实体类对象
                if (anjian != null && anjian.getCasename() != null) {
                    //  DateUtil.getDateByBaseStr(anjian.getCreatetime(),DateUtil.DATE_FORMAT_MINUS);
                    String casename = anjian.getCasename().replaceAll("\r|\n|\t", "");

                    System.out.println("==================================================" + casename + "======++++++++++++++++++++++++++++++++=");
                    // 重新设置casename去掉\r\n
                    anjian.setCasename(casename);
                    //验证此案件是否已插入
                    int exist = policePlatformMapper.verifyCaseExist(anjian.getCasecode());
                    anjian.setId(StringUtil.generatorUUID());
                    if (exist == 0) {
                        String old = anjian.getAccepttime();

                        if (!StringUtil.isEmpty(anjian.getAccepttime())) {
                            Date dd = DateUtil.getDateByBaseStr(anjian.getAccepttime(), DateUtil.LOCATE_DATE_FORMAT);
                            anjian.setAccepttime(DateUtil.formatDate(dd, DateUtil.DATE_FORMAT_MINUS));
                        }

                        if (!StringUtil.isEmpty(anjian.getRecordtime())) {
                            Date dd1 = DateUtil.getDateByBaseStr(anjian.getRecordtime(), DateUtil.LOCATE_DATE_FORMAT);
                            anjian.setRecordtime(DateUtil.formatDate(dd1, DateUtil.DATE_FORMAT_MINUS));
                        }

                        if (!StringUtil.isEmpty(anjian.getEntrydate())) {
                            Date dd2 = DateUtil.getDateByBaseStr(anjian.getEntrydate(), DateUtil.LOCATE_DATE_FORMAT);
                            anjian.setEntrydate(DateUtil.formatDate(dd2, DateUtil.DATE_FORMAT_MINUS));
                        }
                        cases.add(anjian);
                    }
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        System.out.println("案件集合信息5" + "=========================================================" + cases);
        if (cases.size() > 0) {
            for (int i = 0; i < cases.size() - 1; i++) {
                for (int j = cases.size() - 1; j > i; j--) {
                    if (cases.get(j).getCasecode().equals(cases.get(i).getCasecode())) {
                        cases.remove(j);
                    }
                }
            }
            //插入获取到的此单位的案件信息
            policePlatformMapper.insertCasesMessage(cases);
        }

        // 插入此案件相关涉案人员
        for (Cases temp : cases) {
            // 发送请求获取此案件相关涉案人员
            List<SuspectVos> suspects = getSuspecByCaseNum(temp.getCasecode());
            if (suspects.size() == 0) {
                continue;
            }
            // 将此案件涉案人员插入数据库中
            policePlatformMapper.insertSuspect(suspects);
        }

    }

    // 获取相关案件的涉案人员

    private List<SuspectVos> getSuspecByCaseNum(String caseNum) {
        // String uri=serviceUrl+"/police/getSuspect";
        Map<String, String> map = new HashMap<>();
        // 存入查询的案件编码
        map.put("caseNum", caseNum);
        // 发送请求获取相关案件涉案人员
        // String suspecData=httpClientForJL.doGet(uri,map,"utf-8");
        List<Map> maps = inquestionsMapper.getSuspect(map);
        // 将这些人员存入集合当中
        // List<Map> maps=objectMapper.readValue(suspecData,List.class);
        List<SuspectVos> list = new ArrayList<>();

        for (Map m : maps) {
            String suspectString = null;
            try {
                suspectString = objectMapper.writeValueAsString(m);
                SuspectVos suspect = objectMapper.readValue(suspectString, SuspectVos.class);
                suspect.setId(StringUtil.generatorUUID());
                list.add(suspect);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 获取考核信息详情
     *
     * @param
     * @return
     */
    @Transactional
    @Override
    public void grtAssessment(String unitCode, String date, String registTime) {
        Examination examination = new Examination();
        //1,比例考核分数统计
        List<Examination> list = policePlatformMapper.grtTranscriptExamination(unitCode, date, registTime);//获取该月有效案件数量
        List<String> str = policePlatformMapper.grtExaminationCase(unitCode, date, registTime);//获取该月有效案件名称
        List<String> cases = policePlatformMapper.getUploadTranscriptsCase(unitCode, date, registTime);//获取该月已经上传笔录的案件名称
        List resultList = new ArrayList();
        if (cases.size() != 0) {
            for (String item : cases) {//遍历str
                if (str.contains(item)) {//如果存在这个数
                    resultList.add(item);//放进一个list里面，这个list就是交集
                }
            }
        }
        if (resultList.size() == 0 || str.size() == 0) {
            examination.setRecordsProportion("0");
        }
        if (resultList.size() == str.size() && resultList.size() != 0 && str.size() != 0) {
            examination.setRecordsProportion("0");
        }
        if (resultList.size() != 0 && str.size() != 0) {
            String result = getPropotion(resultList.size(), str.size());
            examination.setRecordsProportion(result);
        }

        //3案件基础信息考核
        //求该月有效的所有受理案件
        int i = policePlatformMapper.selectAcceptCase(unitCode, date, registTime);
        //求有效案件个数
        int j = policePlatformMapper.selectEffectiveCase(unitCode, date, registTime);
        if (i == 0 || j == 0) {
            examination.setBasicInformationProportion("0");
        }
        if (i == j && i != 0 && j != 0) {
            examination.setBasicInformationProportion("0");
        }
        if (i != 0 && j != 0) {
            String result = getPropotion(i, j);
            examination.setBasicInformationProportion(result);
        }

        //4,案件涉案人员信息登记考核
        //查询所有案件下有嫌疑人的有效案件编号
        List<String> K = policePlatformMapper.selectPersonnelInformationAssessment(unitCode, date, registTime);
        //查询国家人员信息的案件编号
        List<String> stringList = policePlatformMapper.selectStatePersonnel(unitCode, date, registTime);
        List resultList1 = new ArrayList();
        for (String item : stringList) {//遍历str
            if (K.contains(item)) {//如果存在这个数
                resultList1.add(item);//放进一个list里面，这个list就是交集
            }
        }
        if (K.size() == 0 || resultList1.size() == 0) {
            examination.setPersonnelInformationProportion("0");
        }
        if (K.size() == resultList1.size() && K.size() != 0 && resultList1.size() != 0) {
            examination.setPersonnelInformationProportion("0");
        }
        if (K.size() != 0 && resultList1.size() != 0) {
            String result = getPropotion(K.size(), stringList.size());
            examination.setPersonnelInformationProportion(result);
        }
        int M = 10;
        examination.setMon(date);
        examination.setHandleUnitCode(unitCode);
        examination.setId(StringUtil.generatorUUID());
        //examination.setAssessmentRatio(String.valueOf((Integer.parseInt(examination.getRecordsProportion())+
        //Integer.parseInt(examination.getBasicInformationProportion())+Integer.parseInt(examination.getPersonnelInformationProportion()))*100)+"%");

        Map map = new HashMap();
        map.put("unitCode", unitCode);
        map.put("date", date);
        //验证此考核记录是否已插入
        int exist = policePlatformMapper.selectExist(map);
        if (exist == 0) {
            policePlatformMapper.insertExamineRatio(examination);//考核比例的新增
        }

    }

    public String getPropotion(int i, int j) {
        // 创建一个数值格式化对象
        DecimalFormat df = new DecimalFormat("0.00");
        String result = df.format((float) j / i);
        return result;
        //examination.setRecordsProportion(result);
    }

    @Override
    public int updateWarning(String id) {
        log.info("id:{}", JSONObject.toJSONString(id));
        return policePlatformMapper.updateWarning(id);
    }

    @Override
    public List<AlarmLog> selectAll(WarningVo warningVo) {
        log.info("warningVo:{}", JSONObject.toJSONString(warningVo));
        List<AlarmLog> list = null;
        String[] unicodes = warningVo.getUnitCodes().split(",");
        try {
            PageHelper.startPage(warningVo.getPageNum(), warningVo.getPageSize());
            list = policePlatformMapper.selectAll(unicodes, warningVo.getStatus(), warningVo.getStartDate(), warningVo.getEndDate());
            for (AlarmLog vo : list) {
                String a = vo.getCreateDate();
                int i = a.indexOf(".");
                vo.setCreateDate(a.substring(0, i));
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<Examination> selectExaminationStatistics(Examination examination) {
        List<Examination> list = null;

        String[] uniCodes = examination.getUnitCodes().split(",");
        examination.setArray(uniCodes);
        try {
            PageHelper.startPage(examination.getPageNum(), examination.getPageSize());
            if (examination.getState().equals("0")) {
                list = policePlatformMapper.selectExaminationStatistics(examination);
            } else {
                list = policePlatformMapper.selectExaminationRandom(examination);
                if (list.size() != 0) {
                    policePlatformMapper.updateExaminationRandom(examination);
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }

        return list;
    }

    @Override
    public void ExaminationInfoReport(Examination examination, HttpServletResponse response) {
        try {
            List<Examination> list = null;
            List<Map<String, String>> dataList = Lists.newArrayList();
            String[] uniCodes = examination.getUnitCodes().split(",");
            examination.setArray(uniCodes);
//            for (int i=0;i<=uniCodes.length;i++){
//                if(StringUtil.isEmpty(uniCodes[i])){
//                    String str=uniCodes[i];
//                }
//            }
            String code = uniCodes[0];
            String parentUnitName = "";
            if (code.equals("422800000000")) {
                parentUnitName = "恩施州公安局";
            } else {
                parentUnitName = policePlatformMapper.getParentUnitName(code);//获取父单位名称
            }
            if (examination.getState().equals("0")) {
                list = policePlatformMapper.selectExaminationStatistics(examination);
            } else {
                list = policePlatformMapper.selectExaminationRandom(examination);
            }
            for (Examination examination1 : list) {
                Map<String, String> dataMap = new HashMap<>();
                dataMap.put("单位名称", examination1.getOrganizationName());
                dataMap.put("案件笔录录入", examination1.getRecordsProportion());
                dataMap.put("案件基本信息", examination1.getBasicInformationProportion());
                dataMap.put("人员信息登记", examination1.getPersonnelInformationProportion());
                dataMap.put("文书制作规范", examination1.getClericalExaminationProportion());
                dataMap.put("行政处罚决定公开", examination1.getPunishmentBookProportion());
                dataMap.put("案件受立案公开", examination1.getPubliEExaminationOfCasesProportion());
                // dataMap.put("占比所在的月份", examination1.getMon());
                dataList.add(dataMap);
            }
            String sheetName = "月度考核信息导出列表.xls";
            String[] columnName = {"单位名称", "案件笔录录入", "案件基本信息", "人员信息登记", "文书制作规范", "行政处罚决定公开", "案件受立案公开"};
            Workbook wb = ExcelUtil.getInstance().dataToExcel(dataList, sheetName, columnName, parentUnitName, examination.getMon());
            OutputStream output = null;
            output = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(sheetName.getBytes("UTF-8"), "ISO8859-1"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
            wb.write(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
//		String str="导出成功";
//		return str;
    }

    @Override
    public List<Map> findCaseAccepptHandle(String[] unitCodes) {
        List<Map> map = policePlatformMapper.findCaseAccepptHandle(unitCodes);
        return map;
    }

    @Override
    public DateMount findCaseStatusNum(String[] unitCodes) {
        DateMount dateMount = new DateMount();
        policePlatformMapper.findCaseStatusNum(unitCodes);
        return dateMount;
    }

    @Override
    public Map<String, List<Integer[]>> findCaseCountByUnitCode(String[] unitCode) {
        if (unitCode == null || unitCode.length == 0) {
            return null;
        }
        List<DateVo> list = policePlatformMapper.findCaseCountByUnitCode(Arrays.asList(unitCode));
        Map<String, List<Integer[]>> returnList = new HashMap<>();

        List<Integer[]> titleList = new ArrayList<>();
        List<Integer[]> valueList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            Integer[] title = new Integer[1];
            title[0] = list.get(i).getThisYear();
            titleList.add(title);
            Integer[] value = new Integer[12];
            value[0] = list.get(i).getMonth1();
            value[1] = list.get(i).getMonth2();
            value[2] = list.get(i).getMonth3();
            value[3] = list.get(i).getMonth4();
            value[4] = list.get(i).getMonth5();
            value[5] = list.get(i).getMonth6();
            value[6] = list.get(i).getMonth7();
            value[7] = list.get(i).getMonth8();
            value[8] = list.get(i).getMonth9();
            value[9] = list.get(i).getMonth10();
            value[10] = list.get(i).getMonth11();
            value[11] = list.get(i).getMonth12();
            valueList.add(value);
        }
        returnList.put("title", titleList);
        returnList.put("value", valueList);
        return returnList;
    }

    //查询前年年内各类案件的数量信息
    @Override
    public Map<String, Object> findBeforeYearsCase(String[] array) {
        Map<String, Object> map = new HashMap<>();
        List<DateVo> threeYearsCase = policePlatformMapper.findBeforeYearsCase(array);
        List<String> titleList = new ArrayList<>();
        List<Integer[]> sumList = new ArrayList<>();
        List<Integer[]> valueList = new ArrayList<>();
        ArrayList<String> title = new ArrayList<>();
        int sum = 0;
        for (int i = 0; i < threeYearsCase.size(); i++) {
            titleList.add(threeYearsCase.get(i).getYearAndCaseType().substring(5));
            title.add(threeYearsCase.get(i).getYearAndCaseType());
            Integer[] sumCase = new Integer[1];
            sum = (threeYearsCase.get(i).getMonth1() + threeYearsCase.get(i).getMonth2() +
                    threeYearsCase.get(i).getMonth3() + threeYearsCase.get(i).getMonth4() +
                    threeYearsCase.get(i).getMonth5() + threeYearsCase.get(i).getMonth6() +
                    threeYearsCase.get(i).getMonth7() + threeYearsCase.get(i).getMonth8() +
                    threeYearsCase.get(i).getMonth9() + threeYearsCase.get(i).getMonth10() +
                    threeYearsCase.get(i).getMonth11() + threeYearsCase.get(i).getMonth12());
            threeYearsCase.get(i).setSum(sum);
            Integer[] value = new Integer[12];
            sumCase[0] = threeYearsCase.get(i).getSum();
            value[0] = threeYearsCase.get(i).getMonth1();
            value[1] = threeYearsCase.get(i).getMonth2();
            value[2] = threeYearsCase.get(i).getMonth3();
            value[3] = threeYearsCase.get(i).getMonth4();
            value[4] = threeYearsCase.get(i).getMonth5();
            value[5] = threeYearsCase.get(i).getMonth6();
            value[6] = threeYearsCase.get(i).getMonth7();
            value[7] = threeYearsCase.get(i).getMonth8();
            value[8] = threeYearsCase.get(i).getMonth9();
            value[9] = threeYearsCase.get(i).getMonth10();
            value[10] = threeYearsCase.get(i).getMonth11();
            value[11] = threeYearsCase.get(i).getMonth12();
            valueList.add(value);
            sumList.add(sumCase);
        }
        map.put("title", title);
        map.put("titleList", titleList);
        map.put("sum", sumList);
        map.put("value", valueList);
        return map;
    }

    //查询去年内各类案件的数量信息
    @Override
    public Map<String, Object> findLastYearsCase(String[] array) {
        Map<String, Object> map = new HashMap<>();
        List<DateVo> threeYearsCase = policePlatformMapper.findLastYearsCase(array);
        List<String> titleList = new ArrayList<>();
        List<Integer[]> sumList = new ArrayList<>();
        List<Integer[]> valueList = new ArrayList<>();
        ArrayList<String> title = new ArrayList<>();
        int sum = 0;
        for (int i = 0; i < threeYearsCase.size(); i++) {
            titleList.add(threeYearsCase.get(i).getYearAndCaseType().substring(5));
            title.add(threeYearsCase.get(i).getYearAndCaseType());
            Integer[] sumCase = new Integer[1];
            sum = (threeYearsCase.get(i).getMonth1() + threeYearsCase.get(i).getMonth2() +
                    threeYearsCase.get(i).getMonth3() + threeYearsCase.get(i).getMonth4() +
                    threeYearsCase.get(i).getMonth5() + threeYearsCase.get(i).getMonth6() +
                    threeYearsCase.get(i).getMonth7() + threeYearsCase.get(i).getMonth8() +
                    threeYearsCase.get(i).getMonth9() + threeYearsCase.get(i).getMonth10() +
                    threeYearsCase.get(i).getMonth11() + threeYearsCase.get(i).getMonth12());
            threeYearsCase.get(i).setSum(sum);
            Integer[] value = new Integer[12];
            sumCase[0] = threeYearsCase.get(i).getSum();
            value[0] = threeYearsCase.get(i).getMonth1();
            value[1] = threeYearsCase.get(i).getMonth2();
            value[2] = threeYearsCase.get(i).getMonth3();
            value[3] = threeYearsCase.get(i).getMonth4();
            value[4] = threeYearsCase.get(i).getMonth5();
            value[5] = threeYearsCase.get(i).getMonth6();
            value[6] = threeYearsCase.get(i).getMonth7();
            value[7] = threeYearsCase.get(i).getMonth8();
            value[8] = threeYearsCase.get(i).getMonth9();
            value[9] = threeYearsCase.get(i).getMonth10();
            value[10] = threeYearsCase.get(i).getMonth11();
            value[11] = threeYearsCase.get(i).getMonth12();
            valueList.add(value);
            sumList.add(sumCase);
        }
        map.put("title", title);
        map.put("titleList", titleList);
        map.put("sum", sumList);
        map.put("value", valueList);
        return map;
    }

    //查询今年内各类案件的数量信息
    @Override
    public Map<String, Object> findThisYearsCase(String[] array) {
        Map<String, Object> map = new HashMap<>();
        List<DateVo> threeYearsCase = policePlatformMapper.findThisYearsCaseNew(array);
        List<String> titleList = new ArrayList<>();
        List<Integer[]> sumList = new ArrayList<>();
        List<Integer[]> valueList = new ArrayList<>();
        ArrayList<String> title = new ArrayList<>();
        int sum = 0;
        for (int i = 0; i < threeYearsCase.size(); i++) {
            titleList.add(threeYearsCase.get(i).getYearAndCaseType().substring(5));
            title.add(threeYearsCase.get(i).getYearAndCaseType());
            Integer[] sumCase = new Integer[1];
            sum = (threeYearsCase.get(i).getMonth1() + threeYearsCase.get(i).getMonth2() +
                    threeYearsCase.get(i).getMonth3() + threeYearsCase.get(i).getMonth4() +
                    threeYearsCase.get(i).getMonth5() + threeYearsCase.get(i).getMonth6() +
                    threeYearsCase.get(i).getMonth7() + threeYearsCase.get(i).getMonth8() +
                    threeYearsCase.get(i).getMonth9() + threeYearsCase.get(i).getMonth10() +
                    threeYearsCase.get(i).getMonth11() + threeYearsCase.get(i).getMonth12());
            threeYearsCase.get(i).setSum(sum);
            Integer[] value = new Integer[12];
            sumCase[0] = threeYearsCase.get(i).getSum();
            value[0] = threeYearsCase.get(i).getMonth1();
            value[1] = threeYearsCase.get(i).getMonth2();
            value[2] = threeYearsCase.get(i).getMonth3();
            value[3] = threeYearsCase.get(i).getMonth4();
            value[4] = threeYearsCase.get(i).getMonth5();
            value[5] = threeYearsCase.get(i).getMonth6();
            value[6] = threeYearsCase.get(i).getMonth7();
            value[7] = threeYearsCase.get(i).getMonth8();
            value[8] = threeYearsCase.get(i).getMonth9();
            value[9] = threeYearsCase.get(i).getMonth10();
            value[10] = threeYearsCase.get(i).getMonth11();
            value[11] = threeYearsCase.get(i).getMonth12();
            valueList.add(value);
            sumList.add(sumCase);
        }
        map.put("title", title);
        map.put("titleList", titleList);
        map.put("sum", sumList);
        map.put("value", valueList);
        return map;
    }

    //查询三年内完成案件的信息
    @Override
    public Map<String, Object> findThreeYearsEndCase(String handleUnitCode) {

        Map<String, Object> map = new HashMap<>();
        //如果为恩施州查询县市数据
        if("422800000000".equals(handleUnitCode)){
            List<EndCaseVo> threeYearsList = policePlatformMapper.findBeforeYearsEndCase1();
            List<EndCaseVo> twoYearsList = policePlatformMapper.findLastYearsEndCase1();
            List<EndCaseVo> oneYearsList = policePlatformMapper.findThisYearsEndCase1();

            List<String> yearList = new ArrayList<>();
            List<String> threeyearList = new ArrayList<>();
            List<String> twoyearList = new ArrayList<>();
            List<String> oneyearList = new ArrayList<>();

            List<List<String>> orgList = new ArrayList<>();
            List<String> orgThreeyears = new ArrayList<>();
            List<String> orgztwoyears = new ArrayList<>();
            List<String> orgOneyears = new ArrayList<>();

            List<List<Integer>> totalList = new ArrayList<>();
            List<Integer> totaThreeyearsList = new ArrayList<>();
            List<Integer> totalTwoyearsList = new ArrayList<>();
            List<Integer> totalOneyearsList = new ArrayList<>();

            for (int i = 0; i < threeYearsList.size(); i++) {
                threeyearList.add(threeYearsList.get(i).getYear());
                totaThreeyearsList.add(threeYearsList.get(i).getTotal());
                orgThreeyears.add(threeYearsList.get(i).getOrgName());
            }
            for (int i = 0; i < twoYearsList.size(); i++) {
                twoyearList.add(twoYearsList.get(i).getYear());
                totalTwoyearsList.add(twoYearsList.get(i).getTotal());
                orgztwoyears.add(twoYearsList.get(i).getOrgName());
            }
            for (int i = 0; i < oneYearsList.size(); i++) {
                oneyearList.add(oneYearsList.get(i).getYear());
                totalOneyearsList.add(oneYearsList.get(i).getTotal());
                orgOneyears.add(oneYearsList.get(i).getOrgName());
            }

            totalList.add(totaThreeyearsList);
            totalList.add(totalTwoyearsList);
            totalList.add(totalOneyearsList);

            orgList.add(orgThreeyears);
            orgList.add(orgztwoyears);
            orgList.add(orgOneyears);

            //进行年份去重
            LinkedHashSet<String> set1 = new LinkedHashSet<String>(threeyearList.size());
            set1.addAll(threeyearList);
            threeyearList.clear();
            threeyearList.addAll(set1);

            LinkedHashSet<String> set2 = new LinkedHashSet<String>(twoyearList.size());
            set2.addAll(twoyearList);
            twoyearList.clear();
            twoyearList.addAll(set2);

            LinkedHashSet<String> set3 = new LinkedHashSet<String>(oneyearList.size());
            set3.addAll(oneyearList);
            oneyearList.clear();
            oneyearList.addAll(set3);

            yearList.add(threeyearList.get(0));
            yearList.add(twoyearList.get(0));
            yearList.add(oneyearList.get(0));

            map.put("year", yearList);
            map.put("orgName", orgList);
            map.put("total", totalList);
            return map;
        }else{
            String array[] = null;
            if (!StringUtil.isEmpty(handleUnitCode)) {
                List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
                array = childCode.toArray(new String[childCode.size()]);
            }

            List<EndCaseVo> threeYearsList = policePlatformMapper.findBeforeYearsEndCase(array);
            List<EndCaseVo> twoYearsList = policePlatformMapper.findLastYearsEndCase(array);
            List<EndCaseVo> oneYearsList = policePlatformMapper.findThisYearsEndCase(array);

            List<String> yearList = new ArrayList<>();
            List<String> threeyearList = new ArrayList<>();
            List<String> twoyearList = new ArrayList<>();
            List<String> oneyearList = new ArrayList<>();

            List<List<String>> orgList = new ArrayList<>();
            List<String> orgThreeyears = new ArrayList<>();
            List<String> orgztwoyears = new ArrayList<>();
            List<String> orgOneyears = new ArrayList<>();

            List<List<Integer>> totalList = new ArrayList<>();
            List<Integer> totaThreeyearsList = new ArrayList<>();
            List<Integer> totalTwoyearsList = new ArrayList<>();
            List<Integer> totalOneyearsList = new ArrayList<>();

            if(threeYearsList.size()>0){
                for (int i = 0; i < threeYearsList.size(); i++) {
                    threeyearList.add(threeYearsList.get(i).getYear());
                    totaThreeyearsList.add(threeYearsList.get(i).getTotal());
                    orgThreeyears.add(threeYearsList.get(i).getOrgName());
                }
                totalList.add(totaThreeyearsList);
                orgList.add(orgThreeyears);
                //进行年份去重
                LinkedHashSet<String> set1 = new LinkedHashSet<String>(threeyearList.size());
                set1.addAll(threeyearList);
                threeyearList.clear();
                threeyearList.addAll(set1);
                yearList.add(threeyearList.get(0));
            }
           if(twoYearsList.size()>0){
               for (int i = 0; i < twoYearsList.size(); i++) {
                   twoyearList.add(twoYearsList.get(i).getYear());
                   totalTwoyearsList.add(twoYearsList.get(i).getTotal());
                   orgztwoyears.add(twoYearsList.get(i).getOrgName());
               }
               totalList.add(totalTwoyearsList);
               orgList.add(orgztwoyears);
               LinkedHashSet<String> set2 = new LinkedHashSet<String>(twoyearList.size());
               set2.addAll(twoyearList);
               twoyearList.clear();
               twoyearList.addAll(set2);
               yearList.add(twoyearList.get(0));
           }
           if(oneYearsList.size()>0){
               for (int i = 0; i < oneYearsList.size(); i++) {
                   oneyearList.add(oneYearsList.get(i).getYear());
                   totalOneyearsList.add(oneYearsList.get(i).getTotal());
                   orgOneyears.add(oneYearsList.get(i).getOrgName());
               }
               totalList.add(totalOneyearsList);
               orgList.add(orgOneyears);
               LinkedHashSet<String> set3 = new LinkedHashSet<String>(oneyearList.size());
               set3.addAll(oneyearList);
               oneyearList.clear();
               oneyearList.addAll(set3);
               yearList.add(oneyearList.get(0));
           }
            map.put("year", yearList);
            map.put("orgName", orgList);
            map.put("total", totalList);

            return map;
        }
    }

    @Override
    public Map<String, List<Object>> findPassCaseCountByUnitCode(String[] unitCodeS, String status) {
        Map<String, List<Object>> map = new HashMap<>();

        List<Object> title = new ArrayList<>();// 单位名称
        List<Object> value = new ArrayList<>();// 单位材料通过审核案件数
        for (int i = 0; i < unitCodeS.length; i++) {
            UnitVo caseCount = policePlatformMapper.findPassCaseCountByUnitCode(status, unitCodeS[i]);
            if (caseCount.getOrganizationName() != null) {
                title.add(caseCount.getOrganizationName());
                value.add(caseCount.getCaseCount());
            } else {
                log.info("查询不到该单位信息：unitCode=" + unitCodeS[i]);
                // title.add("无名称");
                // value.add(0);
            }
        }
        map.put("title", title);
        map.put("value", value);
        return map;
    }

    @Override
    public DateMount findToDayNum(String[] unitCodes) {
        int allSuspect = 0;
        int leaveSuspect = 0;
        int presentSuspect = 0;
        List<DateMount> mounts = policePlatformMapper.findToDayNum(unitCodes);
        DateMount dateMount = new DateMount();
        for (DateMount mount : mounts) {
            allSuspect += mount.getAllSuspect();
            leaveSuspect += mount.getLeaveSuspect();
            presentSuspect += mount.getPresentSuspect();
        }
        dateMount.setAllSuspect(allSuspect);
        dateMount.setLeaveSuspect(leaveSuspect);
        dateMount.setPresentSuspect(presentSuspect);
        return dateMount;
    }

    @Override
    public DateMount getProportion(String[] unitCodes) {
        List<DateMount> mounts = policePlatformMapper.getProportion(unitCodes);
        DateMount dateMount = new DateMount();
        int toDay = 0;
        int yesterDay = 0;
        int thisWeek = 0;
        int lastWeek = 0;
        for (DateMount mount : mounts) {
            toDay += mount.getToDay();
            yesterDay += mount.getYesterDay();
            thisWeek += mount.getThisWeek();
            lastWeek += mount.getLastWeek();

        }
        dateMount.setToDay(toDay);
        dateMount.setYesterDay(yesterDay);
        dateMount.setLastWeek(lastWeek);
        dateMount.setThisWeek(thisWeek);
        if (yesterDay > 0) {
            if (toDay > yesterDay) {
                dateMount.setDayStaus(1);// 上涨
            } else {
                dateMount.setDayStaus(0);// 下降
            }
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) Math.abs(toDay - yesterDay) / (float) yesterDay * 100);

            dateMount.setDayProperty(result + "%");
        } else {
            if (toDay > 0) {
                dateMount.setDayStaus(1);
                dateMount.setDayProperty("100%");

            } else {
                dateMount.setDayStaus(1);
                dateMount.setDayProperty("0%");
            }
        }
        if (lastWeek > 0) {
            if (thisWeek > lastWeek) {
                dateMount.setWeekStaus(1);
            } else {
                dateMount.setWeekStaus(0);
            }
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String resulWeek = numberFormat.format((float) Math.abs(lastWeek - thisWeek) / (float) lastWeek * 100);
            dateMount.setWeekProperty(resulWeek + "%");
        } else {
            if (thisWeek > 0) {
                dateMount.setWeekStaus(1);
                dateMount.setWeekProperty("100%");
            } else {
                dateMount.setWeekStaus(1);
                dateMount.setWeekProperty("0%");
            }
        }
        return dateMount;
    }

    @Override
    public DateMount selectRoomInUse(String[] unitCodes) {
        int inUseNum = 0;
        int allNum = 0;
        List<DateMount> mounts = policePlatformMapper.selectRoomInUse(unitCodes);
        DateMount dateMount = new DateMount();
        for (DateMount mount : mounts) {
            inUseNum += mount.getInUseRoom();// 累加集合中对象的在使用房间属性
            allNum += mount.getAllRoom();// 累加集合中对象的多有房间
        }
        dateMount.setInUseNum(inUseNum);
        dateMount.setAllNum(allNum);
        return dateMount;
    }

    @Override
    public DateMount selectOvertimeMan(String[] unitCodes) {

        return policePlatformMapper.selectOvertimeMan(unitCodes);
    }

    @Override
    public DateMount selectAwaitingTrial(String[] unitCodes) {
        int allSuspect = 0;
        int overTimeSuspect = 0;
        List<DateMount> mounts = policePlatformMapper.selectAwaitingTrial(unitCodes);
        DateMount dateMount = new DateMount();
        for (DateMount mount : mounts) {
            allSuspect += mount.getAllSuspect();// 累加集合中对象的在使用房间属性
            overTimeSuspect += mount.getOverTimeSuspect();// 累加集合中对象的多有房间
        }
        dateMount.setAllSuspect(allSuspect);
        dateMount.setOverTimeSuspect(overTimeSuspect);
        return dateMount;
    }

    @Override
    public DateMount caseStatistics(String[] unitCodes) {
        int criminalCase = 0;
        int civilCase = 0;
        int politicsCase = 0;
        int allCase = 0;
        List<DateMount> mounts = policePlatformMapper.caseStatistics(unitCodes);
        DateMount dateMount = new DateMount();
        for (DateMount mount : mounts) {
            criminalCase += mount.getCriminalCase();
            civilCase += mount.getCivilCase();
            politicsCase += mount.getPoliticsCase();
            allCase += mount.getAllCase();
        }
        dateMount.setCriminalCase(criminalCase);
        dateMount.setCivilCase(civilCase);
        dateMount.setPoliticsCase(politicsCase);
        dateMount.setAllCase(allCase);
        return dateMount;
    }

    @Override
    public Map<String, List<Object>> findMaterialCountByUnitCode(String[] unitCodes) {
        Map<String, List<Object>> map = new HashMap<>();

        List<Object> title = new ArrayList<>();// 卷宗材料出入柜状态
        title.add("未入柜");
        title.add("在柜");
        title.add("借阅");
        title.add("移交");
        List<Object> value = new ArrayList<>();// 卷宗材料出入柜状态数据
        Integer notCabinetCount = 0;
        Integer liveCabinetCount = 0;
        Integer borrowCount = 0;
        Integer transferCount = 0;
        Integer borrowOutCount = 0;
        for (int i = 0; i < unitCodes.length; i++) {
            CabinetVo caseCount = policePlatformMapper.findMaterialCountByUnitCode(unitCodes[i]);
            if (caseCount != null) {
                notCabinetCount += caseCount.getNotCabinet();
                liveCabinetCount += caseCount.getLiveCabinet();
                borrowCount += caseCount.getBorrow();
                transferCount += caseCount.getTransfer();
                borrowOutCount += caseCount.getBorrowOutCount();
            }
        }
//		// suspectIds 嫌疑人id(,)逗号分割
//		String suspectIds = policePlatformMapper.findSuspectIdByUnitCodes(unitCodes);
//		CabinetVo caseCount = policePlatformMapper.findMaterialCountBySuspectIds(suspectIds);
        value.add(notCabinetCount);
        value.add(liveCabinetCount);
        value.add(borrowCount);
        value.add(transferCount);
        value.add(borrowOutCount);
        map.put("title", title);
        map.put("value", value);
        return map;
    }

    @Override
    public DateMount selectManAndWoMan(String[] unitCodes) {
        int allManNum = 0;
        int woManNum = 0;
        int manNum = 0;
        DateMount dateMount = new DateMount();

        DateMount dateMounts = policePlatformMapper.selectManAndWoMan(unitCodes);

        dateMount.setAllManNum(dateMounts.getAllManNum());
        dateMount.setWoManNum(dateMounts.getWoManNum());
        dateMount.setManNum(dateMounts.getManNum());
        return dateMount;
    }

    @Override
    public List<CabinetVo> findMaterialCountByUnitCodeAndLibraryStatus(String[] unitCodes, String libraryStatus) {
        if (StringUtil.isEmpty(libraryStatus) || unitCodes == null || unitCodes.length == 0) {
            return null;
        }
        List<CabinetVo> infoList = null;
        CabinetVo cv = null;
        infoList = new ArrayList<>();
        for (int i = 0; i < unitCodes.length; i++) {
            cv = new CabinetVo();
            cv = policePlatformMapper.findLibraryStatusInfo(unitCodes[i], libraryStatus);
            cv.setUnitCode(unitCodes[i]);
            infoList.add(cv);// 查询卷宗是否在柜是否借阅是否移交的状态信息
        }
        return infoList;
    }

    @Override
    public List<CabinetVo> findListMaterialCountByUnitCode(String[] unitCodes) {
        List<CabinetVo> infoList = null;
        CabinetVo cv = null;
        infoList = new ArrayList<>();
        for (int i = 0; i < unitCodes.length; i++) {
            cv = new CabinetVo();
            cv = policePlatformMapper.findMaterialCountByUnitCode(unitCodes[i]);
            cv.setUnitCode(unitCodes[i]);
            infoList.add(cv);// 查询卷宗是否在柜是否借阅是否移交的状态信息
        }
        return infoList;
    }

    @Override
    public void requestAwarning() {
        System.out.println("开始执行获取告警提醒定时任务!" + new Date());

        List<String> list = policePlatformMapper.selectUnicode();
        System.out.println(list);
        String[] strings = new String[list.size()];
        String[] unitCodes = list.toArray(strings);
        selectAllWarning(unitCodes);

        System.out.println("任务执行结束!" + new Date());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    //定时任务调用该方法
    public Map<String, List> selectAllWarning(String[] unitCodes) {

        Map<String, List> map = new HashMap<>();

        try {
            //设备警告提醒和卷宗超期提醒
            for (int i = 0; i < unitCodes.length; i++) {
                //告警提醒记录列表中最大入库时间
                String equipmentRegistTime = policePlatformMapper.findMaxEquipmentTime(unitCodes[i]);//摄像头2
                String auditRegistTime = policePlatformMapper.findMaxauditTime(unitCodes[i]);//卷宗6
                String cabinetTime = policePlatformMapper.findMaxCabinetTime(unitCodes[i]);//案管柜3
                String recorderTime = policePlatformMapper.findMaxRecorder(unitCodes[i]);//记录仪1
                String writerTime = policePlatformMapper.findMaxwriterTime(unitCodes[i]);//刻录机4
                String scanisterTime = policePlatformMapper.findMaxscanisterTime(unitCodes[i]);//扫描仪5
                WarningVo warningVo = new WarningVo();

                warningVo.setEquipmentRegistTime(equipmentRegistTime);
                warningVo.setAuditRegistTime(auditRegistTime);
                warningVo.setCabinetTime(cabinetTime);
                warningVo.setRecorderTime(recorderTime);
                warningVo.setWriterTime(writerTime);
                warningVo.setScanisterTime(scanisterTime);

                warningVo.setHandleUnitCode(unitCodes[i]);
                //查询大于告警提醒时间的记录
                List<WarningVo> Equipments = policePlatformMapper.selectAllEquipmentWarning(warningVo);//摄像头2
                List<WarningVo> audits = policePlatformMapper.selectAllAuditWarning(warningVo);//卷宗6
                List<WarningVo> cabinets = policePlatformMapper.selectAllCabinetWarning(warningVo);//案管柜3
                List<WarningVo> recorders = policePlatformMapper.selectAllRecorderWarning(warningVo);//记录仪1
                List<WarningVo> writers = policePlatformMapper.selectAllWriterWarning(warningVo);//刻录机4
                List<WarningVo> scanisters = policePlatformMapper.selectAllScanisterWarning(warningVo);//扫描仪5

                for (WarningVo recorderVo : recorders) {
                    if (recorderVo != null) {
                        recorderVo.setId(StringUtil.generatorUUID());
                        recorderVo.setAlarmType("1");
                        recorderVo.setCreatTime(recorderVo.getModifyDate());
                        policePlatformMapper.insertEquipmentAlarmLog(recorderVo);//记录仪1记录仪告警提醒告警类型
                    }
                }

                for (WarningVo EquipmentVo : Equipments) {
                    if (EquipmentVo != null) {
                        String id = StringUtil.generatorUUID();
                        EquipmentVo.setId(id);
                        EquipmentVo.setAlarmType("2");//设备告警提醒告警类型为2且为摄像头告警提醒
                        EquipmentVo.setCreatTime(EquipmentVo.getModifyDate());
                        policePlatformMapper.insertEquipmentAlarmLog(EquipmentVo);
                    }
                }
                for (WarningVo cabinetVo : cabinets) {
                    if (cabinetVo != null) {
                        String id = StringUtil.generatorUUID();
                        cabinetVo.setId(id);
                        cabinetVo.setAlarmType("3");//案管柜3且为案管柜告警提醒
                        cabinetVo.setCreatTime(cabinetVo.getModifyDate());
                        policePlatformMapper.insertEquipmentAlarmLog(cabinetVo);
                    }
                }

                for (WarningVo writersVo : writers) {
                    if (writersVo != null) {
                        String id = StringUtil.generatorUUID();
                        writersVo.setId(id);
                        writersVo.setAlarmType("4");//刻录机4且为刻录机告警提醒
                        writersVo.setCreatTime(writersVo.getModifyDate());
                        policePlatformMapper.insertEquipmentAlarmLog(writersVo);
                    }
                }
                for (WarningVo scanistersVo : scanisters) {
                    if (scanistersVo != null) {
                        String id = StringUtil.generatorUUID();
                        scanistersVo.setId(id);
                        scanistersVo.setAlarmType("5");//扫描仪5且为扫描仪告警提醒
                        scanistersVo.setCreatTime(scanistersVo.getModifyDate());
                        policePlatformMapper.insertEquipmentAlarmLog(scanistersVo);
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (WarningVo auditVo : audits) {
                    if (auditVo != null) {
                        String id = StringUtil.generatorUUID();
                        auditVo.setId(id);
                        auditVo.setAlarmType("6");
                        String time1 = auditVo.getBorrowDate();
                        String time2 = auditVo.getMaterialOutDay();
                        String alarmTime = time1 + time2;
                        auditVo.setCreatTime(alarmTime);
                        policePlatformMapper.insertAuditAlarmLog(auditVo);
                    }
                }

                map.put("Equipments" + String.valueOf(i), Equipments);
                map.put("audit" + String.valueOf(i), audits);
            }
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return map;
    }

    @Override
    public List<AlarmLog> selectAllByUnitcode(WarningVo warningVo) {
        log.info("warningVo:{}", JSONObject.toJSONString(warningVo));
        List<AlarmLog> list = null;
        try {
            PageHelper.startPage(warningVo.getPageNum(), warningVo.getPageSize());
            list = policePlatformMapper.selectAllByUnitcode(warningVo);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;

    }

    // 递归查询本单位及其所有子单位信息
    private List<OrganizationVo> UnitInfoEX(String unitCode, String parentId, List<OrganizationVo> childListEX) {

        com.jielin.handling.entity.unit.Organization parentO = unitMapper.findUnitInfoByCode(unitCode);// 查询本单位信息
        if (parentO == null) {
            return new ArrayList<>();
        }

        OrganizationVo thisParent = new OrganizationVo();
        thisParent.setOrgId(parentO.getId());
        thisParent.setHandleUnitCode(parentO.getHandleUnitCode());
        thisParent.setOrgName(parentO.getOrganizationName());
        thisParent.setSite(StringUtil.isEmpty(parentO.getSite()) ? "" : parentO.getSite());
        thisParent.setSuperId(parentId);
        thisParent.setSelected(true);
        childListEX.add(thisParent);

        List<com.jielin.handling.entity.unit.Organization> thisChildO = unitMapper.findChildUnitInfoById(parentO.getId());// 查询当前单位子单位信息

        if (StringUtil.isEmpty(unitCode)) {
            return new ArrayList<>();
        } else if (thisChildO.size() > 0) {
            for (com.jielin.handling.entity.unit.Organization childO : thisChildO) {
                UnitInfoEX(childO.getHandleUnitCode(), parentO.getId(), childListEX);
            }
        }
        return childListEX;
    }

    @Override
    public List<OrganizationVo> findUnitInfoByUnitCodeS(String unitCodes) {
        return UnitInfoEX(unitCodes, "-1", new ArrayList<>());
    }

    /*
    三合一数据同步信息
    */
    @Override
    public void getRecordInfo() {
        List<String> list = policePlatformMapper.getExistInChms();//求两个数据库的并集
        System.out.println(list + "====================================地址集合");
        if (list.size() == 0) {
            return;
        }
        for (String str : list) {
            //通过录音编号查询录音
            RecordInfo recordInfo = policePlatformMapper.selectRecordInfoById(str);
            if (recordInfo == null || StringUtil.isEmpty(recordInfo.getSPath())) {
                return;
            }
            System.out.println(recordInfo + "====================================查询到的对象");
            String folderPath = ConstantUtil.VIOCE_PATH + "involvedVoice" + File.separator;
            // 获取当前时间毫秒数拼接
            String trueFileName = String.valueOf(System.currentTimeMillis());
            URL url = null;
            int value = 0;
            String filePath = "";
            byte[] b = null;
            DataInputStream dataInputStream = null;
            try {
                //拼接音频服务器全路径地址
                System.out.println("真实地址" + ConstantUtil.VIOCE_URL + recordInfo.getSPath());
                url = new URL(ConstantUtil.VIOCE_URL + recordInfo.getSPath());
                dataInputStream = new DataInputStream(url.openStream());
            } catch (Exception e) {
                System.out.println("输入流转换失败");
                return;
            }
            //生成文件夹
            File folderFile = new File(folderPath);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
            }
            String fileType = recordInfo.getSPath().substring(recordInfo.getSPath().lastIndexOf("."));
            //String fileType=".mp3";
            filePath = ConstantUtil.VIOCE_URL + folderPath + trueFileName + fileType;//数据库存储访问路劲
            // recordInfo.setSPath(filePath);
            //拼接存储文件路径
            String path = folderPath + trueFileName + fileType;//磁盘存储文件绝对路径
            //设置新的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            path = path.replace("\\", "/");
            if (ConstantUtil.XSKYRESTORAGE) {
                meta.setContentType("audio/x-wav");
                try {
                    xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, path, dataInputStream, meta);
                } catch (Exception e) {
                    log.error(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                    System.out.println("xsky存储失败" + path + "===================");
                    return;
                }
                recordInfo.setSPath(ConstantUtil.XSKY_PREPATH_URL + path);
                recordInfo.setId(StringUtil.generatorUUID());
                //文件上传的方式
                recordInfo.setUploadType("1");
                //将数据存入到我们自己的数据库
                policePlatformMapper.insetRecordInfo(recordInfo);
            } else {
                //文件上传的方式
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                } catch (Exception e) {
                    System.out.println("流下载失败" + path + "===================");
                }

                recordInfo.setUploadType("0");
                recordInfo.setId(StringUtil.generatorUUID());
                recordInfo.setSPath(ConstantUtil.returnIp() + path);
                //将数据存入到我们自己的数据库
                policePlatformMapper.insetRecordInfo(recordInfo);
            }

        }
        System.out.println("数据上传成功!!!!!!!!");
    }

    @Override
    public List<RecordInfo> selectRecordInfol(RecordInfo recordInfo) {
        return policePlatformMapper.selectRecordInfol(recordInfo);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateRecordInfo(int M, String id, String documentId, String fileDocPath, String Spath) {
        int i = 0;
        String trueFileName = "";
        MaterialFile materialFile = new MaterialFile();
        //截取文件名称
        String fileName = Spath.substring(Spath.lastIndexOf("/") + 1, Spath.lastIndexOf("."));
        trueFileName = fileName;
        //文件类型
        String fileType = Spath.substring(Spath.lastIndexOf("."));
        String path = ConstantUtil.FILE_PATH + fileDocPath + trueFileName + fileType;
        path = path.replace("\\", "/");
        ObjectMetadata meta = new ObjectMetadata();
        try {
            if (M == 0) {
                meta.setContentType("audio/x-wav");
                xskyService.copyObject(ConstantUtil.XSKY_BUCKET_DOSSIER, Spath.substring(ConstantUtil.XSKY_PREPATH_URL.length()), ConstantUtil.XSKY_BUCKET_DOSSIER, path, meta);
                System.out.println("1111111111111111111111111111111111111111111111111111111");
            }
            if (M == 1) {
                //拼接音频服务器全路径地址
//                URL url = new URL(Spath);
//                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                System.out.println(Spath.substring(ConstantUtil.returnIp().length()) + "=================================================");
                File file = new File(Spath.substring(ConstantUtil.returnIp().length()));
                xskyService.uploadObjectThrows(ConstantUtil.XSKY_BUCKET_DOSSIER, path, file);
            }
            try {
                //更新已关联
                policePlatformMapper.updateRecordInfo(id);
                //文件表中插入一条心的记录
                materialFile.setFilename(fileName);
                materialFile.setId(StringUtil.generatorUUID());
                materialFile.setMaterialtypedocumentid(documentId);
                materialFile.setUrl(ConstantUtil.XSKY_PREPATH_URL + path);
                materialFile.setThumbnailpath(ConstantUtil.WEB_MP3FILE_PATH);
                materialFile.setFilename(fileName);
                materialFile.setFiletype(fileType);
                maTypeDocumentMapper.updateDocAddCount(documentId);
                mfMapper.addFile(materialFile);
                i = 1;
            } catch (Exception e) {
                log.info("sql执行异常", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

        } catch (Exception e) {
            System.out.println("XSKY上的音频同步失败");
            System.out.println(e);
        }
        return i;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateInfoOnServer(int M, String id, String documentId, String fileDocPath, String Spath) {
        int i = 0;
        String trueFileName = "";
        MaterialFile materialFile = new MaterialFile();
        //截取文件名称
        String fileName = Spath.substring(Spath.lastIndexOf("/") + 1, Spath.lastIndexOf("."));
        trueFileName = fileName;
        //文件类型
        String fileType = Spath.substring(Spath.lastIndexOf("."));
        String path = ConstantUtil.FILE_PATH + fileDocPath + trueFileName + fileType;
        DataInputStream dataInputStream = null;
        try {
            if (M == 0) {
                try {
                    //拼接音频服务器全路径地址
                    URL url = new URL(Spath);
                    dataInputStream = new DataInputStream(url.openStream());

                } catch (Exception e) {
                    System.out.println("输入流转换失败");
                    return i;
                }
                //生成文件夹
                File folderFile = new File(ConstantUtil.FILE_PATH + fileDocPath);
                if (!folderFile.exists()) {
                    folderFile.mkdirs();
                }
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                } catch (Exception e) {
                    System.out.println("流下载失败" + path + "===================");
                    return i;
                }
            } else {
                System.out.println(Spath.substring(ConstantUtil.returnIp().length()));
                File file = new File(Spath.substring(ConstantUtil.returnIp().length()));
                try {
                    System.out.println(path + "////////////////////////////////////////");
                    FileUtil.copyFile(file, new File(path));
                } catch (IOException e) {
                    System.out.println("文件复制错误");
                    return i;
                }
            }
            try {
                //更新已关联
                policePlatformMapper.updateRecordInfo(id);
                //文件表中插入一条心的记录
                materialFile.setFilename(fileName);
                materialFile.setId(StringUtil.generatorUUID());
                materialFile.setMaterialtypedocumentid(documentId);
                materialFile.setUrl(ConstantUtil.returnIp() + path);
                materialFile.setThumbnailpath(ConstantUtil.WEB_MP3FILE_PATH);
                materialFile.setFilename(fileName);
                materialFile.setFiletype(fileType);
                maTypeDocumentMapper.updateDocAddCount(documentId);
                mfMapper.addFile(materialFile);
                i = 1;
            } catch (Exception e) {
                log.info("sql执行异常", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

        } catch (Exception e) {
            System.out.println("服务器音频同步失败");
        }
        return i;

    }

    @Override
    public Map selectCallPolice(String[] array) {
        //求110报警总数
        int i = policePlatformMapper.selectForJJDB_110(array);
        //求119报警总数
        int j = policePlatformMapper.selectForJJDB_119(array);
        //求122报警总数
        int m = policePlatformMapper.selectForJJDB_122(array);
        //总数
        int allCount = i + j + m;
        Map<String, List<Object>> map = new HashMap<>();

        List<Object> title = new ArrayList<>();// 卷宗材料出入柜状态
        title.add("110报警总数");
        title.add("119报警总数");
        title.add("122报警总数");
        title.add("总数");
        List<Object> value = new ArrayList<>();

        value.add(i);
        value.add(j);
        value.add(m);
        value.add(allCount);
        map.put("title", title);
        map.put("value", value);
        return map;
    }

    public static String returnRation(int num1, int num2) {
        String relation = "";
        if (num1 == 0 && num2 == 0) {
            relation = "0%";
        }
        if (num1 != 0 && num2 == 0 || num1 == 0 && num2 != 0) {
            relation = "0%";
        }
        if (num1 != 0 && num2 != 0) {
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) num2 / (float) num1 * 100);
            relation = result + "%";
        }
        return relation;
    }

    @Override
    public Map<String, Object> selectPoliceSituation(String handleUnitCode) {
        String array[] = null;

        if (!StringUtil.isEmpty(handleUnitCode)) {

            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());

            array = childCode.toArray(new String[childCode.size()]);

        }
        //查询上个月的事件总数
        int j = policePlatformMapper.selectLastMonth(array);
        //查询上上月的事件总数
        int k = policePlatformMapper.selectThisMonth(array);
        //查询处警事件比例
        String ration = returnRation(k, j - k);
        Map<String, Object> map = new HashMap();
        map.put("ration", ration);
        //查询有效警情总数和上个月和本月的数据
//        CallPoliceProportion callPoliceProportion = policePlatformMapper.selectEffectivePolice(array);
        //有效警情的总数
//        int countForEffectivePolice = callPoliceProportion.getCount();
        //有效警情上个月的总数
//        int lastCountForEffectivePolice = callPoliceProportion.getLastCounnt();
        //有效警情当月的总数
//        int thisForEffectivePolice = callPoliceProportion.getThisCounnt();
        //查询有效警情比例
//        String rationForEffective = returnRation(lastCountForEffectivePolice, thisForEffectivePolice - lastCountForEffectivePolice);

        //有效警情上个月的总数
        int lastCountForEffectivePolice = policePlatformMapper.selectEffectivePolice2_110(array) + policePlatformMapper.selectEffectivePolice2_119(array) + policePlatformMapper.selectEffectivePolice2_122(array);
        //有效警情上上月的总数
        int thisForEffectivePolice = policePlatformMapper.selectEffectivePolice3_110(array) + policePlatformMapper.selectEffectivePolice3_119(array) + policePlatformMapper.selectEffectivePolice3_122(array);
        //查询有效警情比例
        String rationForEffective = returnRation(thisForEffectivePolice, lastCountForEffectivePolice - thisForEffectivePolice);

        map.put("rationForEffective", rationForEffective);
        //查询接警事件
//        CallPoliceProportion callPoliceProportion3 = policePlatformMapper.selectReceiveThePolice(array);
        //查询接警事件总数
//        int countForReceiveThePolice = callPoliceProportion3.getCount();
        //查询上个月接警事件的总数
//        int lastCountForRceiveThePolice = callPoliceProportion3.getLastCounnt();
        //查询当月接警事件的总数
//        int thisCountForRceiveThePolice = callPoliceProportion3.getThisCounnt();
        //接警的比例
//        String rationReceiveThePolice = returnRation(lastCountForRceiveThePolice, thisCountForRceiveThePolice - lastCountForRceiveThePolice);

        //查询上个月接警事件的总数
        int lastCountForRceiveThePolice = policePlatformMapper.selectReceiveThePolice2_110(array) + policePlatformMapper.selectReceiveThePolice2_119(array) + policePlatformMapper.selectReceiveThePolice2_122(array);
        //查询上上月接警事件的总数
        int thisCountForRceiveThePolice = policePlatformMapper.selectReceiveThePolice3_110(array) + policePlatformMapper.selectReceiveThePolice3_119(array) + policePlatformMapper.selectReceiveThePolice3_122(array);
        //接警的比例
        String rationReceiveThePolice = returnRation(thisCountForRceiveThePolice, lastCountForRceiveThePolice - thisCountForRceiveThePolice);

        map.put("rationReceiveThePolice", rationReceiveThePolice);
        //查询无效警情
//        CallPoliceProportion callPoliceProportion4 = policePlatformMapper.selectInvalidThePolice(array);
        //查询无效警情总数
//        int invalidPoliceCount = callPoliceProportion4.getInvalidPoliceCount();
        //查询上个月无效警情总数
//        int lastInvalidPoliceCount = callPoliceProportion4.getLastInvalidPoliceCount();
        //查询当月无效警情总数
//        int thisInvalidPoliceCount = callPoliceProportion4.getThisInvalidPoliceCount();
        //查询无效警情的比例
//        String rationInvalidPolice = returnRation(invalidPoliceCount, thisInvalidPoliceCount - lastInvalidPoliceCount);

        //查询上个月无效警情总数
        int lastInvalidPoliceCount = policePlatformMapper.selectInvalidThePolice2_110(array) + policePlatformMapper.selectInvalidThePolice2_119(array) + policePlatformMapper.selectInvalidThePolice2_122(array);
        //查询上上月无效警情总数
        int thisInvalidPoliceCount = policePlatformMapper.selectInvalidThePolice3_110(array) + policePlatformMapper.selectInvalidThePolice3_119(array) + policePlatformMapper.selectInvalidThePolice3_122(array);
        //查询无效警情的比例
        String rationInvalidPolice = returnRation(thisInvalidPoliceCount, lastInvalidPoliceCount - thisInvalidPoliceCount);
        map.put("rationInvalidPolice", rationInvalidPolice);
        //查询重大警情
//        CallPoliceProportion callPoliceProportion5 = policePlatformMapper.selectBigPolice(array);
        //重大警情总数
//        int bigCount = callPoliceProportion5.getBigCount();
        //重大警情上个月的总数
//        int lastBigCount = callPoliceProportion5.getLastBigCount();
        //重大警情当月的总数
//        int thisBigCount = callPoliceProportion5.getThisBigCount();
        //重大警情比例
//        String rationbigPolice = returnRation(lastBigCount, thisBigCount - lastBigCount);

        //重大警情上个月的总数
        int lastBigCount = policePlatformMapper.selectBigPolice2_110(array) + policePlatformMapper.selectBigPolice2_119(array) + policePlatformMapper.selectBigPolice2_122(array);
        //重大警情上上月的总数
        int thisBigCount = policePlatformMapper.selectBigPolice3_110(array) + policePlatformMapper.selectBigPolice3_119(array) + policePlatformMapper.selectBigPolice3_122(array);
        //重大警情比例
        String rationbigPolice = returnRation(thisBigCount, lastBigCount - thisBigCount);
        map.put("rationbigPolice", rationbigPolice);
        //涉外警情
//        CallPoliceProportion callPoliceProportion6 = policePlatformMapper.selectOutPolice(array);
        //涉外警情总数
//        int outCount = callPoliceProportion6.getOutCount();
        //涉外上个月警情总数
//        int lastOutCount = callPoliceProportion6.getLastOutCount();
        //涉外查询当月警情总数
//        int thisOutCount = callPoliceProportion6.getThisOutCount();
//        String rationOutPolice = returnRation(lastOutCount, thisOutCount - lastOutCount);

        //涉外上个月警情总数
        int lastOutCount = policePlatformMapper.selectOutPolice2_110(array) + policePlatformMapper.selectOutPolice2_119(array) + policePlatformMapper.selectOutPolice2_122(array);
        //涉外查询上上月警情总数
        int thisOutCount = policePlatformMapper.selectOutPolice3_110(array) + policePlatformMapper.selectOutPolice3_119(array) + policePlatformMapper.selectOutPolice3_122(array);
        String rationOutPolice = returnRation(thisOutCount, lastOutCount - thisOutCount);
        map.put("rationOutPolice", rationOutPolice);
        //   redisTemplateX.set("selectPoliceSituation",list);
        return map;
    }

    @Override
    public int selectPoliceSituationCountByCode(String handleUnitCode) {
        return policePlatformMapper.selectPoliceSituationCountByCode(handleUnitCode);
    }
    @Override
    public void addPoliceSituation(PoliceSituationMiddle policeSituationMiddle) {
        policePlatformMapper.addPoliceSituation(policeSituationMiddle);
    }

    @Override
    public int countForCJPolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年处警事件总数
        return policePlatformMapper.selectFor_CJDB(array);
    }
    @Override
    public int countForEffectivePolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年有效警情的总数
        return policePlatformMapper.selectEffectivePolice1_110(array) + policePlatformMapper.selectEffectivePolice1_119(array) + policePlatformMapper.selectEffectivePolice1_122(array);

    }
    @Override
    public Map<String, Object> countForReceiveThePolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年接警事件总数
        int countForReceive_110 = policePlatformMapper.selectReceiveThePolice1_110(array);
        int countForReceive_119 = policePlatformMapper.selectReceiveThePolice1_119(array);
        int countForReceive_122 = policePlatformMapper.selectReceiveThePolice1_122(array);
        Map<String, Object> map = new HashMap();
        map.put("countForReceive_110", countForReceive_110);
        map.put("countForReceive_119", countForReceive_119);
        map.put("countForReceive_122", countForReceive_122);
        map.put("countForReceiveThePolice", countForReceive_110+countForReceive_119+countForReceive_122);
        return map;
    }
    @Override
    public int countForInvalidPolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年无效警情总数
        return policePlatformMapper.selectInvalidThePolice1_110(array) + policePlatformMapper.selectInvalidThePolice1_119(array) + policePlatformMapper.selectInvalidThePolice1_122(array);

    }
    @Override
    public int countForBigPolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年重大警情总数
        return policePlatformMapper.selectBigPolice1_110(array) + policePlatformMapper.selectBigPolice1_119(array) + policePlatformMapper.selectBigPolice1_122(array);

    }
    @Override
    public int countForOutPolice(String handleUnitCode) {
        String array[] = null;
        if (!StringUtil.isEmpty(handleUnitCode)) {
            List<String> childCode = getChildCode(handleUnitCode, new ArrayList<>(), unitMapper.findAllUnitInfo());
            array = childCode.toArray(new String[childCode.size()]);
        }
        //查询今年涉外警情总数
        return policePlatformMapper.selectOutPolice1_110(array) + policePlatformMapper.selectOutPolice1_119(array) + policePlatformMapper.selectOutPolice1_122(array);

    }

    @Override
    public List<CallPoliceProportion> selectPoliceDetails(CallPoliceProportion cp) {
        List<CallPoliceProportion> list = null;
        Map<String, String> map = new HashMap();
        String[] array = cp.getUnitCodes().split(",");
        cp.setArray(array);
        list = policePlatformMapper.selectPoliceDetails(cp);
        if (list.size() != 0) {
            for (CallPoliceProportion callPoliceProportion : list) {
                //通过单位编号查询处警事件数量
                int i = policePlatformMapper.selectFor_CJDBByUnitCode(callPoliceProportion.getUnitCode());
                callPoliceProportion.setHandleCase(i);
                //通过单位编号查询接警数量
                int k = policePlatformMapper.selectFor_receivedCase(callPoliceProportion.getUnitCode());
                callPoliceProportion.setReceivedCase(k);
//                //接警所占比例
//                callPoliceProportion.setReceivedCaseRation(callPoliceProportion.getReceivedCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getReceivedCase()) + ")");
//                //处警所占比例
//                callPoliceProportion.setHandleCaseRation(callPoliceProportion.getHandleCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getHandleCase()) + ")");
//                //有效警情所占比例
//                callPoliceProportion.setEffectiveCaseRation(callPoliceProportion.getEffectiveCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getEffectiveCase()) + ")");
//                //无效警情所占比例
//                callPoliceProportion.setInvalidCaseRation(callPoliceProportion.getInvalidCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getInvalidCase()) + ")");
//                //重大警情所占比例
//                callPoliceProportion.setBigCaseRation(callPoliceProportion.getBigCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getBigCase()) + ")");
//                //涉外警情所占比例
//                callPoliceProportion.setOutCaseRation(callPoliceProportion.getOutCase() + "(" + returnRation(callPoliceProportion.getReceivedCase(), callPoliceProportion.getOutCase()) + ")");
//                //单位名称
                Map maps = policePlatformMapper.selectOrgName(callPoliceProportion.getUnitCode());
                callPoliceProportion.setOrgName((String) maps.get("name"));
                callPoliceProportion.setOrgId((String) maps.get("id"));

            }
        }
        Collections.sort(list, new Comparator<CallPoliceProportion>(){
            @Override
            public int compare(CallPoliceProportion p1, CallPoliceProportion p2) {
                int sort = p1.getReceivedCase() - p2.getReceivedCase();
                if(sort == 0){
                    return p1.getHandleCase() - p2.getHandleCase();
                }
                return sort;
            }
        });
        return list;
    }

    @Override
    public List<PoliceSituationVo> selectPoliceSituationByUnicode(PoliceSituationVo vo) {
        List<PoliceSituationVo> list = null;
        try {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            list = policePlatformMapper.selectPoliceSituationByUnicode(vo);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    private static Integer comparingByValue(Map<String, Integer> map) {
        return map.values().iterator().next();
    }

    @Override
    public List<Map<String, Object>> selectCriminalCase(String[] array) {
        List<Map<String, Object>> list = new ArrayList<>();
        CriminalCase criminalCase = policePlatformMapper.selectCriminalCase(array);
        HashMap<String, Object> map0 = new HashMap<String, Object>();
        map0.put("num", "违反治安管理行政案件");
        map0.put("id", criminalCase.getPublicSecurityCase());
        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("num", "侵犯财产");
        map1.put("id", criminalCase.getMoneyCase());
        HashMap<String, Object> map2 = new HashMap<String, Object>();
        map2.put("num", "侵害国防利益");
        map2.put("id", criminalCase.getNationalDefenseCase());
        HashMap<String, Object> map3 = new HashMap<String, Object>();
        map3.put("num", "侵犯人身公民权利，民主");
        map3.put("id", criminalCase.getFreedomCase());
        HashMap<String, Object> map4 = new HashMap<String, Object>();
        map4.put("num", "妨害社会管理秩序");
        map4.put("id", criminalCase.getSocialOrderCase());
        HashMap<String, Object> map5 = new HashMap<String, Object>();
        map5.put("num", "危害公共安全");
        map5.put("id", criminalCase.getPublicCase());
        HashMap<String, Object> map6 = new HashMap<String, Object>();
        map6.put("num", "贪污受贿");
        map6.put("id", criminalCase.getCorruptionAndBriberyCase());
        HashMap<String, Object> map7 = new HashMap<String, Object>();
        map7.put("num", "违反娱乐场所管理行政案件");
        map7.put("id", criminalCase.getEntertainmentCase());
        HashMap<String, Object> map8 = new HashMap<String, Object>();
        map8.put("num", "破坏社会主义市场经济");
        map8.put("id", criminalCase.getSocioeconomicCase());
        HashMap<String, Object> map9 = new HashMap<String, Object>();
        map9.put("num", "违反特种行业管理行政案件");
        map9.put("id", criminalCase.getSpecialCase());
        list.add(map0);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        list.add(map5);
        list.add(map6);
        list.add(map7);
        list.add(map8);
        list.add(map9);
        list.sort(Comparator.comparingInt(o -> Integer.parseInt(o.get("id").toString())));
        System.out.println(list);
        Collections.reverse(list);
        System.out.println(list);
        return list;
    }

    @Override
    public Map<String, Object> selectStatistics(UnitInfo unitInfo) {
        Map<String, Object> map = new HashMap();
        List<Organization> lists = null;

        List<Organization> list = null;

        if ("0".equals(unitInfo.getType())) {
            //查询所有细类别的名称和类型编号（32种细类别的名称）
            lists = policePlatformMapper.selectSortType();
            //查询所有案件的数量
            int i = policePlatformMapper.selectAllCaseNum(unitInfo);
            for (Organization vo : lists) {
                //根据案件的类型统计该细类别的数量
                unitInfo.setType(vo.getType().substring(0, 2));
                int j = policePlatformMapper.selectCountByType(unitInfo);
                String ration = returnRation(i, j);
                vo.setAllCaseSortRation(ration);
                vo.setTypeNum(j);
            }
            list = policePlatformMapper.selectCaseSort(unitInfo.getArray());
        }

        if ("1".equals(unitInfo.getType())) {
            switch(unitInfo.getUnitCodes()){
                //恩施州
                case "422800000000":
                    List<Map<String,Object>> SumEsz= policePlatformMapper.selectStatisticsESZ();
                    list = policePlatformMapper.selectStatistics(unitInfo);
                    if(list.size()>0){
                        for (int i = 0; i <list.size() ; i++) {
                            list.get(i).setSumCriminalCase(SumEsz.get(i).get("sumCriminalCase").toString());
                            list.get(i).setSumCivilCase(SumEsz.get(i).get("sumCivilCase").toString());
                            list.get(i).setSumPoliticalCase(SumEsz.get(i).get("sumPoliticalCase").toString());
                        }
                    }
                    break;
                    //恩施市公安局
                case "422801000000":
                    //利川市公安局
                case "422802000000":
                    //来凤县公安局
                case "422827000000":
                    //鹤峰县公安局
                case "422828000000":
                    //建始县公安局
                case "422822000000":
                    //巴东县公安局
                case "422823000000":
                    //咸丰县公安局
                case "422826000000":
                    //宣恩县公安局
                case "422825000000":
                    List<Map<String,Object>> SumEs= policePlatformMapper.selectStatisticsBxs(unitInfo);
                    list = policePlatformMapper.selectStatistics(unitInfo);
                    if(list.size()>0){
                        for (int i = 0; i <list.size() ; i++) {
                            list.get(i).setSumCriminalCase(SumEs.get(i).get("sumCriminalCase").toString());
                            list.get(i).setSumCivilCase(SumEs.get(i).get("sumCivilCase").toString());
                            list.get(i).setSumPoliticalCase(SumEs.get(i).get("sumPoliticalCase").toString());
                        }
                    }
                    break;
                    //八个公安局一起
                case "422801000000,422802000000,422827000000,422828000000,422822000000,422823000000,422826000000,422825000000":
                    List<Map<String,Object>> SumBxs= policePlatformMapper.selectStatisticsBxsAll();
                    list = policePlatformMapper.selectStatistics(unitInfo);
                    if(list.size()>0){
                        for (int i = 0; i <list.size() ; i++) {
                            if("422801000000".equals(list.get(i).getHandleUnitCode())){
                                if("422801000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422802000000".equals(list.get(i).getHandleUnitCode())){
                                if("422802000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422827000000".equals(list.get(i).getHandleUnitCode())){
                                if("422827000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422828000000".equals(list.get(i).getHandleUnitCode())){
                                if("422828000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422822000000".equals(list.get(i).getHandleUnitCode())){
                                if("422822000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422823000000".equals(list.get(i).getHandleUnitCode())){
                                if("422823000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422826000000".equals(list.get(i).getHandleUnitCode())){
                                if("422826000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                            if("422825000000".equals(list.get(i).getHandleUnitCode())){
                                if("422825000000".equals(SumBxs.get(i).get("handleUnitCode"))){
                                    list.get(i).setSumCriminalCase(SumBxs.get(i).get("sumCriminalCase").toString());
                                    list.get(i).setSumCivilCase(SumBxs.get(i).get("sumCivilCase").toString());
                                    list.get(i).setSumPoliticalCase(SumBxs.get(i).get("sumPoliticalCase").toString());
                                }

                            }
                        }
                        Collections.sort(list, new Comparator<Organization>(){
                            @Override
                            public int compare(Organization o1, Organization o2) {
                                return o1.getSort() - o2.getSort();
                            }
                        });
                    }
                    break;
                default:
                    if(!unitInfo.getUnitCodes().isEmpty()){
                        list = policePlatformMapper.selectStatistics(unitInfo);
                    }
            }

        }
        map.put("caseNum", list);
        map.put("sortNum", lists);
        return map;
    }

    @Override
    public List<Map<String, Object>> selectStatisticsSort(UnitInfo unitInfo) {
        Organization vo = policePlatformMapper.selectStatisticsSort(unitInfo);
        vo.setCriminalCaseRation(returnRation(vo.getAllCase(), vo.getCriminalCase()));
        vo.setPoliticalCaseRation(returnRation(vo.getAllCase(), vo.getPoliticalCase()));
        vo.setCivilCaseRation(returnRation(vo.getAllCase(), vo.getCivilCase()));
        Map map1 = new HashMap();
        map1.put("name", "民事案件");
        map1.put("num", vo.getCivilCase());
        map1.put("ration", returnRation(vo.getAllCase(), vo.getCivilCase()));
        map1.put("i", 0);
        Map map2 = new HashMap();
        map2.put("name", "政治案件");
        map2.put("num", vo.getPoliticalCase());
        map2.put("ration", returnRation(vo.getAllCase(), vo.getPoliticalCase()));
        map2.put("i", 0);
        int i = policePlatformMapper.selectCriminalNum();//刑事案件种类个数
        Map map3 = new HashMap();
        map3.put("name", "刑事案件");
        map3.put("num", vo.getCriminalCase());
        map3.put("ration", returnRation(vo.getAllCase(), vo.getCriminalCase()));
        map3.put("i", i);
        vo.setCriminalNum(i);
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        return list;
    }

    @Override
    public List<Organization> selectCriminalCaseSort(UnitInfo unitInfo) {
        //查询所有案件的数量
        int i = policePlatformMapper.selectAllCaseNum(unitInfo);
        //案件细类别案件数量
        int j = policePlatformMapper.selectCriminalCaseAllNum(unitInfo);
        List<Organization> vo = policePlatformMapper.selectCriminalCaseSort(unitInfo);
        for (Organization organization : vo) {
            //查询案件细类别名称
            String sortName = policePlatformMapper.selectSortName(organization.getType() + "000000");
            organization.setSortName(sortName);
            organization.setAllCaseSortRation(returnRation(i, organization.getTypeNum()));
            organization.setAllSortRation(returnRation(j, organization.getTypeNum()));
        }

        return vo;
    }

    @Override
    public int selectOnlinePoliceCount() {
        return policePlatformMapper.selectOnlinePoliceCount();
    }
}